<!DOCTYPE html>
<style>
body {
    height: 2000px;
    width: 2000px;
}
</style>

<div id='console'></div>
<script src="../../resources/js-test.js"></script>
<script>
window.jsTestIsAsync = true;
description('This test verifies that navigating to entries created by ' +
            'pushState or replaceState correctly restores scroll position ' +
            'correctly and respects "scrollRestoration" flag.');

var tests = {
  '#1': {type: 'push',    expectedScroll: [50, 100]},
  '#2': {type: 'replace', expectedScroll: [100, 200]},
  '#3': {type: 'push',    expectedScroll: [150, 300], options: {scrollRestoration: 'auto'}},
  '#4': {type: 'replace', expectedScroll: [200, 400], options: {scrollRestoration: 'auto'}},
  /* Scroll position should not be restored for these two. */
  '#5': {type: 'push',    expectedScroll: [0, 0],     options: {scrollRestoration: 'manual'}},
  '#6': {type: 'replace', expectedScroll: [0, 0],     options: {scrollRestoration: 'manual'}}
};

// Navigation steps:
// 1. Create a history entry using pushState then scroll
// 2. Create a history entry and replace it then scroll
// 3-6. Repeat 1 & 2 with different option values
// 7. Navigate away and come back
// 8-13. Verify 6 to 1 and keep navigating back
function handleNavigation() {
  if (window.name !== 'verification phase') {
    for (var key in tests) {
      var test = tests[key];
      var args = [{key: key}, '', key];

      if (test.type == 'push') {
        history.pushState.apply(history, args);
      } else {
        history.pushState(null, '', key);
        history.replaceState.apply(history, args);
      }

      if ('options' in test)
         history.scrollRestoration = test.options.scrollRestoration;

      window.scrollBy(50, 100);
    }

    setTimeout(function() {
      window.name = 'verification phase';
      window.location.href = 'resources/empty-document-goes-back.html';
    }, 0);
  } else {
    var key = location.hash,
        test = tests[key];

    debug('verifying ' + key);
    shouldBeEqualToString('history.state.key', '' + key);
    shouldBe('document.scrollingElement.scrollLeft', test.expectedScroll[0].toString());
    shouldBe('document.scrollingElement.scrollTop', test.expectedScroll[1].toString());

    if (key !== '#1') {
      window.history.back();
    } else {
      window.name = '';
      finishJSTest();
    }
  }
}

window.addEventListener('pageshow', handleNavigation);
window.addEventListener('hashchange', handleNavigation);
</script>
